// pages/Plan/PlanPage.jsx
import { Customer, CustomerCards, Plans } from "api/queries";
import Box from "components/atoms/Box";
import Loader from "components/atoms/Loader";
import { isAccountActive, isFreeTrial } from "libs/utils";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "react-query";
import { useNavigate } from "react-router-dom";
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { useAuth } from 'contexts/AuthContext';
import PlanCard from "./PlanCard";
import QueryDebugLogger from 'components/debugging/QueryDebugLogger';
import {
  Grid,
  Typography,
  Button,
  ButtonGroup,
  Container,
  Alert,
  AlertTitle,
  useTheme
} from '@mui/material';
import { styled } from '@mui/material/styles';

// Styled components with business aesthetic
const BusinessContainer = styled(Container)(({ theme }) => ({
  padding: theme.spacing(4, 4, 6),
  backgroundColor: '#ffffff',
  borderRadius: '8px',
  boxShadow: '0 6px 20px rgba(0, 0, 0, 0.08)',
  margin: '24px auto',
  position: 'relative',
  overflow: 'hidden',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: '4px',
    background: '#40d47e',
  }
}));

const PageHeader = styled(Typography)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '2.5rem',
  fontWeight: '600',
  textAlign: 'center',
  color: '#2d3748',
  margin: theme.spacing(2, 0, 1),
  position: 'relative',
  '&::after': {
    content: '""',
    position: 'absolute',
    bottom: '-12px',
    left: '50%',
    transform: 'translateX(-50%)',
    width: '80px',
    height: '3px',
    backgroundColor: '#40d47e',
  },
  [theme.breakpoints.down('sm')]: {
    fontSize: '2rem',
  },
}));

const SubHeader = styled(Typography)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '1.125rem',
  textAlign: 'center',
  marginTop: theme.spacing(3),
  marginBottom: theme.spacing(5),
  color: '#718096',
  maxWidth: '700px',
  margin: '24px auto',
  [theme.breakpoints.down('sm')]: {
    fontSize: '1rem',
  },
}));

const WarningBox = styled(Box)(({ theme }) => ({
  padding: theme.spacing(3),
  borderRadius: '8px',
  border: '1px solid #f8bd0b',
  backgroundColor: '#fffbeb',
  marginBottom: theme.spacing(4),
}));

const WarningTitle = styled(Typography)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '1.25rem',
  fontWeight: '600',
  color: '#b45309',
  marginBottom: theme.spacing(2),
}));

const BusinessButtonGroup = styled(ButtonGroup)(({ theme }) => ({
  boxShadow: 'none',
  '.MuiButton-root': {
    boxShadow: 'none',
    borderColor: '#40d47e',
    textTransform: 'none',
    padding: '10px 24px',
    fontWeight: 500,
    fontSize: '0.95rem',
    transition: 'all 0.3s ease',
  },
  '.MuiButton-contained': {
    backgroundColor: '#40d47e',
    color: 'white',
    '&:hover': {
      backgroundColor: '#36bc6f',
    }
  },
  '.MuiButton-outlined': {
    color: '#40d47e',
    '&:hover': {
      backgroundColor: 'rgba(64, 212, 126, 0.08)',
    }
  }
}));

const LoadingBox = styled(Box)(({ theme }) => ({
  textAlign: 'center',
  padding: theme.spacing(6),
  backgroundColor: '#ffffff',
  borderRadius: '8px',
  boxShadow: '0 6px 20px rgba(0, 0, 0, 0.08)',
  margin: '24px auto',
}));

const AlertStyled = styled(Alert)(({ theme }) => ({
  borderRadius: '8px',
  boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
  '.MuiAlert-icon': {
    color: '#e53e3e',
  },
  '.MuiAlertTitle-root': {
    fontFamily: '"Poppins", "Roboto", sans-serif',
    fontSize: '1.125rem',
    fontWeight: '600',
  }
}));

const RefreshButton = styled(Button)(({ theme }) => ({
  backgroundColor: '#40d47e',
  color: 'white',
  textTransform: 'none',
  boxShadow: '0 4px 10px rgba(64, 212, 126, 0.25)',
  padding: '8px 24px',
  fontWeight: 500,
  '&:hover': {
    backgroundColor: '#36bc6f',
    boxShadow: '0 6px 15px rgba(64, 212, 126, 0.35)',
  }
}));

const PlanPage = () => {
  const { user } = useAuth();
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useTheme();
  const [selectedPlanRecurring, setSelectedPlanRecurring] = useState(1);
  const [selectedPlan, setSelectedPlan] = useState(undefined);
  const [currentSubscription, setCurrentSubscription] = useState();
  const [stripePromise, setStripePromise] = useState(null);

  // Navigate when a plan is selected
  useEffect(() => {
    if (selectedPlan !== undefined) {
      navigate(`/plan/${selectedPlan}/subscribe`);
    }
  }, [selectedPlan, navigate]);

  // Customer query - renamed for consistency
  const customerQuery = useQuery("Customer", Customer, {
    retry: false,
    onSuccess: (data) => {
      if (!isFreeTrial(user.account)) {
        try {
          const cs = data?.data?.subscriptions?.data?.[0];
          if (cs) {
            setCurrentSubscription(cs);
          }
        } catch (e) {
          console.error("Error processing subscription:", e);
        }
      }
    },
  });

  // Plans query
  const plansQuery = useQuery(
    "Plans",
    Plans,
    {
      retry: false,
      onSuccess: (data) => {
        // Initialize Stripe with the public key when plans data is loaded
        if (data?.data?.publicKey) {
          setStripePromise(loadStripe(data.data.publicKey));
        }
      },
    }
  );

  // Cards query
  const cardsQuery = useQuery(
    ["CustomerCards", user.accountId],
    CustomerCards,
    {
      retry: false,
    }
  );

  // Prepare queries for debug logger
  const queriesForDebug = [
    {
      name: "Customer Query",
      isLoading: customerQuery.isLoading,
      isError: customerQuery.isError,
      error: customerQuery.error,
      data: customerQuery.data
    },
    {
      name: "Plans Query",
      isLoading: plansQuery.isLoading,
      isError: plansQuery.isError,
      error: plansQuery.error,
      data: plansQuery.data
    },
    {
      name: "Cards Query",
      isLoading: cardsQuery.isLoading,
      isError: cardsQuery.isError,
      error: cardsQuery.error,
      data: cardsQuery.data
    },
    {
      name: "State Variables",
      isLoading: false,
      isError: false,
      data: {
        selectedPlanRecurring,
        selectedPlan,
        currentSubscription,
        stripePromise: stripePromise ? "Loaded" : "Not Loaded"
      }
    }
  ];

  // Loading state
  if (customerQuery.isLoading || plansQuery.isLoading || cardsQuery.isLoading) {
    return (
      <>
        <LoadingBox>
          <Loader />
        </LoadingBox>
        <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
      </>
    );
  }

  // Error handling
  if (customerQuery.isError || plansQuery.isError || cardsQuery.isError) {
    return (
      <Container maxWidth="md">
        <AlertStyled severity="error" sx={{ mt: 3 }}>
          <AlertTitle>{t("common.error")}</AlertTitle>
          {t("planPage.errorLoadingData")}
        </AlertStyled>
        <QueryDebugLogger queries={queriesForDebug} isVisible={true} />
      </Container>
    );
  }

  // Check if plans data is available - FIXED: More explicit check
  if (!plansQuery.data || !plansQuery.data.data || !plansQuery.data.data.plans) {
    return (
      <Container maxWidth="md">
        <Grid container spacing={3} sx={{ mt: 3 }}>
          <Grid item xs={12}>
            <WarningBox>
              <WarningTitle>
                {t("planPage.planDataNotAvailable")}
              </WarningTitle>
              <Typography variant="body1" paragraph sx={{ 
                color: '#6b7280',
                fontSize: '1rem',
                marginBottom: '16px'
              }}>
                {t("planPage.planDataCouldNotBeLoaded")}
              </Typography>
              <ul style={{ color: '#6b7280', paddingLeft: '20px' }}>
                <li style={{ marginBottom: '8px' }}>
                  {t("planPage.plansAPIRequestFailed")}
                </li>
                <li style={{ marginBottom: '8px' }}>
                  {t("planPage.noPlansReturned")}
                </li>
                <li style={{ marginBottom: '8px' }}>
                  {t("planPage.planDataStructureChanged")}
                </li>
              </ul>
              <RefreshButton
                sx={{ mt: 2 }}
                onClick={() => window.location.reload()}
              >
                {t("common.refresh")}
              </RefreshButton>
            </WarningBox>
          </Grid>
        </Grid>
        <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
      </Container>
    );
  }

  // Filter plans by billing interval
  const monthlyPlans = plansQuery.data.data.plans.filter(p => p.monthly) || [];
  const yearlyPlans = plansQuery.data.data.plans.filter(p => !p.monthly) || [];
  const showRecurringToggle = monthlyPlans.length > 0 && yearlyPlans.length > 0;

  // If no plans match the selected interval
  const noPlansToShow = 
    (selectedPlanRecurring === 1 && monthlyPlans.length === 0) || 
    (selectedPlanRecurring === 2 && yearlyPlans.length === 0);

  if (noPlansToShow) {
    return (
      <Container maxWidth="md">
        <Grid container spacing={3} sx={{ mt: 3 }}>
          <Grid item xs={12}>
            <WarningBox>
              <WarningTitle>
                {t("planPage.noPlansAvailable")}
              </WarningTitle>
              <Typography variant="body1" paragraph sx={{ color: '#6b7280' }}>
                {selectedPlanRecurring === 1 
                  ? t("planPage.noMonthlyPlansAvailable") 
                  : t("planPage.noYearlyPlansAvailable")}
              </Typography>
              {showRecurringToggle && (
                <RefreshButton
                  sx={{ mt: 2 }}
                  onClick={() => setSelectedPlanRecurring(selectedPlanRecurring === 1 ? 2 : 1)}
                >
                  {selectedPlanRecurring === 1 
                    ? t("planPage.switchToYearly") 
                    : t("planPage.switchToMonthly")}
                </RefreshButton>
              )}
            </WarningBox>
          </Grid>
        </Grid>
        <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
      </Container>
    );
  }

  // Stripe Elements options
  const options = {
    fonts: [
      {
        cssSrc: 'https://fonts.googleapis.com/css?family=Poppins:400,500,600|Roboto',
      },
    ],
  };

  return (
    <>
      <BusinessContainer maxWidth="lg">
        <PageHeader component="h1">
          {t("planPage.selectaPlan")}
        </PageHeader>
        
        {!isAccountActive(user.account) && (
          <SubHeader>
            {t("planPage.deactivatedAccountNotice")}
          </SubHeader>
        )}
        
        {stripePromise ? (
          <Elements stripe={stripePromise} options={options}>
            <Grid container direction="column" spacing={4}>
              {showRecurringToggle && (
                <Grid item>
                  <BusinessButtonGroup fullWidth>
                    <Button
                      onClick={() => setSelectedPlanRecurring(1)}
                      variant={selectedPlanRecurring === 1 ? "contained" : "outlined"}
                    >
                      {t("planPage.monthly")}
                    </Button>
                    <Button
                      onClick={() => setSelectedPlanRecurring(2)}
                      variant={selectedPlanRecurring === 2 ? "contained" : "outlined"}
                    >
                      {t("planPage.yearly")}
                    </Button>
                  </BusinessButtonGroup>
                </Grid>
              )}

              <Grid item>
                <Grid container spacing={3}>
                  {selectedPlanRecurring === 1 && monthlyPlans.map((plan, i) => (
                    <Grid item xs={12} md={4} key={`monthly-${i}`}>
                      <PlanCard
                        plan={plan}
                        monthly
                        setSelectedPlan={setSelectedPlan}
                        currentSubscription={currentSubscription}
                        cardsData={cardsQuery.data?.data}
                      />
                    </Grid>
                  ))}

                  {selectedPlanRecurring === 2 && yearlyPlans.map((plan, i) => (
                    <Grid item xs={12} md={4} key={`yearly-${i}`}>
                      <PlanCard
                        plan={plan}
                        monthly={false}
                        setSelectedPlan={setSelectedPlan}
                        currentSubscription={currentSubscription}
                        cardsData={cardsQuery.data?.data}
                      />
                    </Grid>
                  ))}
                </Grid>
              </Grid>
            </Grid>
          </Elements>
        ) : (
          <LoadingBox>
            <Loader />
          </LoadingBox>
        )}
      </BusinessContainer>
      <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
    </>
  );
};

export default PlanPage;